package nl.grol.yakshop.web.servlet;

import java.io.IOException;
import java.net.URL;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.grol.yakshop.binding.MyYakShopModule;
import nl.grol.yakshop.dataimporter.HerdImporterI;
import nl.grol.yakshop.dataimporter.XmlHerdImporter;
import nl.grol.yakshop.domain.model.YakHerd;
import nl.grol.yakshop.domain.model.YakI;
import nl.grol.yakshop.web.servlet.json.JsonConverter;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@Singleton
@SuppressWarnings("serial")
public class ImportServlet extends BaseJsonServlet {
    private static final Logger LOGGER = Logger.getLogger(ImportServlet.class.getName());
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		try {

			/*
			 * Get services from guice
			 */
			Injector injector = Guice.createInjector(new MyYakShopModule());
			HerdImporterI importer = injector.getInstance(XmlHerdImporter.class);
			
//			ServletContext context = getServletContext();
//			InputStream is = context.getResourceAsStream("/WEB-INF/herd.xml");
//			YakHerd herd = importer.loadFromInputStream( is );
			
			/*
			 * Display the current herd configuration
			 */
			URL resource = getClass().getClassLoader().getResource("herd.xml");
			YakHerd herd = importer.loadFromResource( resource );

			
			/*
			 * Create json response
			 */
			String herdAsJson = JsonConverter.makeJsonHerd(0, 
									herd.getYaks() );
			
			/*
			 * Write to response body
			 */
			writeSuccessResponse( req, resp, 200, herdAsJson);
			
			
		} catch( Exception exc ) {
			
			writeErrorResponse( req, resp, 500, exc);

		}

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		try {

			/*
			 * Get services from guice
			 */
			Injector injector = Guice.createInjector(new MyYakShopModule());
			HerdImporterI importer = injector.getInstance(XmlHerdImporter.class);
			
			/*
			 * Get xml data from request-body of the HTTP request
			 */
			YakHerd herd = importer.loadFromInputStream( req.getInputStream() );
			
			/*
			 * TODO Persist herd en yaks
			 */
			persistHerd( herd );
			
			/*
			 * Debug
			 */
			LOGGER.info("Herd:" + herd.toString() );
			
			/*
			 * Return success response
			 */
			writeSuccessResponse( req, resp, 200);
			
		} catch( Exception exc ) {
			
			writeErrorResponse( req, resp, 400, exc);

		}

	}

	private void persistHerd( YakHerd herd ) {
		/*
		 * TODO
		 */
		for( YakI yak : herd.getYaks() ) {
			persistYak( yak );
		}

	}
	
	private void persistYak( YakI yak ) {
		/*
		 * TODO
		 */
		
	}
	

}
